package com.demo.ctf;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AcceptEitherDemo {
    public static void main(String[] args) throws Exception {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            // 模拟耗时操作
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IllegalStateException(e);
            }
            return "Result from future 1";
        });

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            // 模拟另一个耗时操作
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IllegalStateException(e);
            }
            return "Result from future 2";
        });

        // 当任意一个future完成时，使用Consumer函数处理结果
        CompletableFuture<Void> resultFuture = future1.acceptEither(future2, (result) -> {
            System.out.println("Result: " + result);
            // 在这里进行基于结果的操作，但不返回新的CompletableFuture
        });
        // 主线程等待，防止程序立即退出
        CompletableFuture.anyOf(future1, future2).join();
    }
}